<?php
require '../../cn-config.php';
$cn_interpret_url = FALSE;
require CN_DOCUMENT_ROOT.'includes/load.php';

$channel = $_REQUEST['channel'];
$last = $_REQUEST['last'];
$limit = $_REQUEST['limit'];
$message = stripslashes($_REQUEST['message']);
$mode = $_REQUEST['method'];
$path = CN_DOCUMENT_ROOT . 'modules/live-chat/log_'.$channel.'.txt';
switch($mode) {
	case 'post':		
		$fh = fopen($path, 'a') or die("can't open file");
		$stringData = "*!*![ ".date('Y-m-d H:i:s')." ]".$message."\n";
		fwrite($fh, $stringData);	
		fclose($fh);
		break;
	case 'read':
		if(file_exists($path)) {
			$contents = file_get_contents($path);
			$contents = explode('*!*!', $contents);
			$count = count($contents) - 1;
			$new_chats = $count - $last;
			if($new_chats < 0) $new_chats = 0;
			if($new_chats) {
				if($new_chats > $limit) $new_chats = $limit;
				for($i = ($count - $new_chats + 1); $i<=$count; $i++) {
					$chats .= '<li>'.substr($contents[$i], 23).'</li>';
				} 
			}
			
			echo json_encode(array('count'=>$new_chats, 'chats'=>$chats, 'last'=>$count));
		}
		else {
			echo 'file does not exist';
		}
		break;
	default:
		echo 'test';
		break;
}	

?>